package com.kfpanda.file.monitor.listener;

import java.io.File;
import java.util.Date;

import javax.annotation.Resource;

import net.contentobjects.jnotify.JNotifyListener;

import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.stereotype.Repository;

import com.kfpanda.file.monitor.bean.FileNotify;

@Repository
public class MongodbListener implements JNotifyListener {
	
	@Resource(name="fileMonitorTemplate")
	MongoOperations mongoOperations;
	
	private boolean saveDir = false;

	@Override
	public void fileCreated(int wd, String rootPath, String name) {
		File file = new File(rootPath + "/" + name);
		FileNotify fileNotify = new FileNotify();
		if(file.isDirectory()){
			fileNotify.setFileType("directory");
		}else{
			fileNotify.setFileType("file");
		}
		fileNotify.setName(name);
		fileNotify.setNotify("created");
		fileNotify.setNotifyTime(new Date().getTime());
		fileNotify.setRootPath(rootPath);
		if(this.saveDir || !file.isDirectory()){
			mongoOperations.insert(fileNotify, fileNotify.collectName());
		}
	}

	@Override
	public void fileDeleted(int wd, String rootPath, String name) {
		File file = new File(rootPath + "/" + name);
		FileNotify fileNotify = new FileNotify();
		if(file.isDirectory()){
			fileNotify.setFileType("directory");
		}else{
			fileNotify.setFileType("file");
		}
		fileNotify.setName(name);
		fileNotify.setNotify("deleted");
		fileNotify.setNotifyTime(new Date().getTime());
		fileNotify.setRootPath(rootPath);
		if(this.saveDir || !file.isDirectory()){
			mongoOperations.insert(fileNotify, fileNotify.collectName());
		}
	}

	@Override
	public void fileModified(int wd, String rootPath, String name) {
		File file = new File(rootPath + "/" + name);
		FileNotify fileNotify = new FileNotify();
		if(file.isDirectory()){
			fileNotify.setFileType("directory");
		}else{
			fileNotify.setFileType("file");
		}
		fileNotify.setName(name);
		fileNotify.setNotify("modified");
		fileNotify.setNotifyTime(new Date().getTime());
		fileNotify.setRootPath(rootPath);
		if(this.saveDir || !file.isDirectory()){
			mongoOperations.insert(fileNotify, fileNotify.collectName());
		}
	}

	@Override
	public void fileRenamed(int wd, String rootPath, String oldName, String newName) {
		File file = new File(rootPath + "/" + oldName);
		FileNotify fileNotify = new FileNotify();
		if(file.isDirectory()){
			fileNotify.setFileType("directory");
		}else{
			fileNotify.setFileType("file");
		}
		fileNotify.setName(oldName);
		fileNotify.setNotify("delete");
		fileNotify.setNotifyTime(new Date().getTime());
		fileNotify.setRootPath(rootPath);
		if(this.saveDir || !file.isDirectory()){
			mongoOperations.insert(fileNotify, fileNotify.collectName());
		}
	}
}
